<?php

class MySQLDB {

	public $connect;

	function __construct($host, $user, $pw, $db) {
		$this->connect($host, $user, $pw, $db);
	}

	public function connect($host, $user, $pw, $db) {
		$this->connect = mysql_connect($host, $user, $pw, $db) or die("Can't connect to database!");
		mysql_select_db($db) or die("Error using database: ".mysql_error()."<br>".mysql_errno());
	}
	
	public function pConnect($host, $user, $pw, $db) {
		$this->connect = mysql_pconnect($host, $user, $pw) or die("Can't connect to database!");
		mysql_select_db($db) or die("Error using database: ".mysql_error()."<br>".mysql_errno());
	}	
	public function disconnect(){
		mysql_close($this->connect);
	}

	public function selectWhere($table, $condition) {
		$result = $this->getResult("select * from ".$table." where ".$condition.";");
		return $result;
	}
	
	public function executeQuery($qry){
		$result = mysql_query($qry)or die("Error in executeQuery: ".mysql_error()."<br>".$qry);
		return $result;
	}
	
	public function delete($table, $condition) {
		$result = $this->getResult("delete from ".$table." where ".$condition.";");
		return $result;
	}

	public function fetchRow($result){
		$row = mysql_fetch_assoc($result);
		if(is_array($row)){
			return $row;
		} else {
			return false;
		}
	}

	public function getResult($qry) {
		$result = mysql_query($qry, $this->connect)or die("Error in getResult: ".mysql_error()."<br>".$qry);
		return $result;
	}

	public function insert($table, $fields, $data) {
		while($this->insertUsed);
		$this->insertUsed = true;
		mysql_query("INSERT INTO ".$table."(".$fields.") VALUES(".$data.");", $this->connect) or die("Error in insert(): ".mysql_error()."<br>".mysql_errno());
		$id = mysql_insert_id($this->connect);
		$this->insertUsed = false;
		return $id;	
	}

	public function update($table, $fieldsData, $condition) {
		mysql_query("update ".$table." SET ".$fieldsData." where ".$condition.";", $this->connect) or die("Error in update(): ".mysql_error()."<br>".mysql_errno());
	}	

	public function getJsonResult($result){
		$rows = array();
		while($row = $this->FetchRow($result)) {
		  $rows[] = $row;
		}
		return json_encode($rows);
	}
}

// extention for persistent connection
class MySQLDBP extends MySQLDB {
   function __construct($host, $user, $pw, $db) {
       parent::pConnect($host, $user, $pw, $db);

   }
}
?>